package com.kmshack.newsstand;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.xmz.sliding360.PagerSlidingTabStripScrollCallback;

/**
 * Created by zengxianming on 2017/10/26.
 * version 1.0
 */
public class MainFragment extends Fragment implements ScrollTabHolder, ViewPager.OnPageChangeListener{
    public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK_INT).intValue() < 11;

    private CostHEventLinearLayout mHeader;

    private PagerSlidingTabStripScrollCallback mPagerSlidingTabStrip;
    private ViewPager mViewPager;
    private PagerAdapter mPagerAdapter;

    private int mMinHeaderHeight;
    private int mHeaderHeight;
    private int mMinHeaderTranslation;

    private ImageView mHeaderIV;

    private TextView info;
    private int mLastY;
    private int translationY;
    private ScrollTabHolder currentHolder;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        initImageLoader();

        mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
        mMinHeaderTranslation = -mMinHeaderHeight;

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main,container,false);

        mHeader = (CostHEventLinearLayout) view.findViewById(R.id.header);
        info = (TextView) view.findViewById(R.id.info);

        mPagerSlidingTabStrip = (PagerSlidingTabStripScrollCallback) view.findViewById(R.id.tabs);
        mViewPager = (ViewPager) view.findViewById(R.id.pager);

        mPagerAdapter = new PagerAdapter(getActivity().getSupportFragmentManager());
        mPagerAdapter.setTabHolderScrollingContent(this);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.addOnPageChangeListener(this);

        mHeaderIV = (ImageView) view.findViewById(R.id.header_vp);

        mPagerSlidingTabStrip.setViewPager(mViewPager);

        //头部滑动事件，通过重写LinearLayout TouchEvent回传
        CostHEventLinearLayout.IScrollUpCallback touchMoveCallback = new CostHEventLinearLayout.IScrollUpCallback() {
            @Override
            public void scrollToY(int actionMoveY,int downY,boolean isFromLayout) {
                int showInScreenHeight = (mHeaderHeight + (actionMoveY - downY));
                Log.e(getClass().getSimpleName(), "showInScreenHeight: " + showInScreenHeight);
                adjustScroll(showInScreenHeight);
            }
        };
        mHeader.setScrollUpCallback(touchMoveCallback);
        mPagerSlidingTabStrip.setScrollUpCallback(touchMoveCallback);

        mLastY = 0;
        return view;
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {
        // nothing
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        if (positionOffsetPixels > 0) {
            int currentItem = mViewPager.getCurrentItem();

            SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
            ScrollTabHolder currentHolder;

            if (position < currentItem) {
                currentHolder = scrollTabHolders.valueAt(position);
            } else {
                currentHolder = scrollTabHolders.valueAt(position + 1);
            }

            if (NEEDS_PROXY) {
                currentHolder.adjustScroll(mHeader.getHeight() - mLastY);
                mHeader.postInvalidate();
            } else {
                currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
            }
        }
    }

    @Override
    public void onPageSelected(int position) {
        SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
        currentHolder = scrollTabHolders.valueAt(position);
        currentHolder.setSelf(this);
        if(NEEDS_PROXY){
            currentHolder.adjustScroll(mHeader.getHeight() - mLastY);
            mHeader.postInvalidate();
        }else{
            currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount, int pagePosition) {
        if (mViewPager.getCurrentItem() == pagePosition) {
            int scrollY = getScrollY(view);
            Log.e(getClass().getSimpleName(), "scrollY:" + scrollY);

            translationY = Math.max(-scrollY, -mHeaderHeight);
            if(NEEDS_PROXY){
                mLastY=-Math.max(-scrollY, mMinHeaderTranslation);
                info.setText(String.valueOf(scrollY));
                mHeader.scrollTo(0, mLastY);
                mHeader.postInvalidate();
            }else{
                mHeader.setTranslationY(Math.max(-scrollY, mMinHeaderTranslation));
            }
        }
    }

    public int getHeaderHeight(){
        return mHeaderHeight;
    }

    @Override
    public void setSelf(Fragment fragment) {
    }

    @Override
    public void adjustScroll(int scrollHeight) {
        Log.i(getTag(),"*************************scrollHeight: " + scrollHeight);
        if(currentHolder != null) {
            currentHolder.adjustScroll(scrollHeight);
        }
    }

    public int getScrollY(AbsListView view) {
        View c = view.getChildAt(0);
        if (c == null) {
            return 0;
        }

        int firstVisiblePosition = view.getFirstVisiblePosition();
        int top = c.getTop();

        int headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = mHeaderHeight;
        }

        return -top + firstVisiblePosition * c.getHeight() + headerHeight;
    }

    public static float clamp(float value, float max, float min) {
        return Math.max(Math.min(value, min), max);
    }

    public class PagerAdapter extends FragmentPagerAdapter {

        private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
        private final String[] TITLES = { "Page 1", "Page 2", "Page 3"};
        private ScrollTabHolder mListener;

        public PagerAdapter(FragmentManager fm) {
            super(fm);
            mScrollTabHolders = new SparseArrayCompat<>();
        }

        public void setTabHolderScrollingContent(ScrollTabHolder listener) {
            mListener = listener;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            ScrollTabHolderFragment fragment = (ScrollTabHolderFragment) SampleListFragment.newInstance(position);

            mScrollTabHolders.put(position, fragment);
            if (mListener != null) {
                fragment.setScrollTabHolder(mListener);
            }

            return fragment;
        }

        public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
            return mScrollTabHolders;
        }

    }

    private void initImageLoader() {
        ImageLoaderConfiguration config =
                new ImageLoaderConfiguration.Builder(getActivity())
                        // .memoryCacheExtraOptions(1280, 1920) // default = device screen dimensions
                        // .diskCacheExtraOptions(1280, 1920, null)
                        .threadPoolSize(3)
                        // default
                        .threadPriority(Thread.NORM_PRIORITY - 2)
                        // default
                        .tasksProcessingOrder(QueueProcessingType.FIFO)
                        .memoryCache(new UsingFreqLimitedMemoryCache(8 * 1024 * 1024))
                        // 限制内存大小
                        .memoryCacheSize(8 * 1024 * 1024)
                        .memoryCacheSizePercentage(10)
                        // default
                        // .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                        .diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
                        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                        .imageDownloader(new BaseImageDownloader(getActivity())) // default
                        .imageDecoder(new BaseImageDecoder(true)) // default
                        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                        .build();

        // 初始化imageLoader
        ImageLoader.getInstance().init(config);
    }
}
